//
//  LS_ComposeView.swift
//  weibo
//
//  Created by 罗李苏 on 16/5/28.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit
import SnapKit
class LS_ComposeView: UIView {
    //保存按钮的数组
    var buttons: [LS_ComposeButton] = [LS_ComposeButton]()
    
    //保存参数, 方便其他地方使用
    weak var target: UIViewController?
    func show(targetVC target: UIViewController) {
        self.target = target
        //添加视图
        target.view.addSubview(self)
    }
    override init(frame: CGRect) {
        //指定大小
        let rect = UIScreen.mainScreen().bounds
        
        super.init(frame: rect)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        //从父视图移除
        for (index,btn) in buttons.reverse().enumerate() {
            startAnimation(btn, index: index,offset: 350)
        }
    }
    
    //将要移动到父视图上之后开始做动画
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(superview)
        
        for (index,btn) in buttons.enumerate() {
            startAnimation(btn, index: index,offset: -350)
        }
    }
    
    private func startAnimation(btn: LS_ComposeButton, index: Int, offset: CGFloat) {
        UIView.animateWithDuration(0.8, delay: Double(index) * 0.02, usingSpringWithDamping: 0.6, initialSpringVelocity: 5, options: [], animations: {
            //修改按钮的y值
            btn.center = CGPoint(x: btn.center.x, y: btn.center.y + offset)
            }, completion: { (_) in
                if offset > 0 {
                    //移除
                    self.removeFromSuperview()
                }
        })
    }

    
    private func setupUI(){
        backgroundColor = UIColor.redColor()
        addSubview(backImageView)
        addSubview(sloganImageView)
        //添加约束
        sloganImageView.snp_makeConstraints { (make) in
            make.centerX.equalTo(self.snp_centerX)
            make.top.equalTo(self.snp_top).offset(100)
        }

        //添加按钮
        addChildButtons()
    }
    private func addChildButtons(){
        //按钮的数量
        let count = composeItems.count
        
        //按钮的大小
        let w:CGFloat = 80
        let h:CGFloat = 120
        let margin = (ScreenWidth - 3 * w) / 4
        
        for i in 0..<count {
            let btn = LS_ComposeButton()
            //设置按钮的图片文字
            let item = composeItems[i]
            btn.composeItem = item
            //添加点击事件
            btn.addTarget(self, action: #selector(LS_ComposeView.btnDidClick(_:)), forControlEvents: .TouchUpInside)
            
            //指定frame
            let row = i / 3
            let col = i % 3
            let x = CGFloat(col) * (margin + w) + margin
            let y = CGFloat(row) * (h + margin) + ScreenHeight
            btn.frame = CGRect(x: x, y: y, width: w, height: h)
            self.addSubview(btn)
            //添加到数组
            buttons.append(btn)
        }
    }
    //MARK:按钮的点击事件
    //被点击的按钮放大
    //其他的按钮缩小
@objc private func btnDidClick(btn: LS_ComposeButton){
    //遍历所有的按钮当前判断是否是被点击的按钮
    for button in buttons {
        var scale: CGFloat = 0
        if button == btn {
            //放大
            scale = 2.0
        }else{
        //缩小
            scale = 0.5
        }
        
        UIView.animateWithDuration(0.25, animations: {
            //修改形变
            button.alpha = 0
            button.transform = CGAffineTransformMakeScale(scale, scale)
            }, completion: { (_) in
                print("OK")
                
        })

    }
    //页面跳转
    //获取控制器的名称
    print(btn.composeItem)
    guard let target = btn.composeItem?.target else {
        return
    }
    let time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 0.3))
    dispatch_after(time_t, dispatch_get_main_queue()) {

    //就是根据字符串来获取控制器对应类型
    let type = NSClassFromString(target) as! UIViewController.Type
    //初始化控制器
    let vc = type.init()
    let nav = UINavigationController(rootViewController: vc)
    //页面跳转  视图不能跳转页面
    self.target?.presentViewController(nav, animated: true, completion: {
        self.removeFromSuperview()
    })
    }
    
    }
    //MARK:懒加载子控件
    private lazy var backImageView: UIImageView = UIImageView(image: UIImage.snapShotCurrentWindow().applyLightEffect())
    
    private lazy var sloganImageView: UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))
    
    private lazy var composeItems: [LS_ComposeItem] = {
    var array = [LS_ComposeItem]()
        //获取文件数组
        
        //文件路径
        let path = NSBundle.mainBundle().pathForResource("Compose.plist", ofType: nil)
        //读取路径下的文件
        let itemArray = NSArray(contentsOfFile: path!) as! [[String : AnyObject]]
        //遍历 字典转模型
        for item in itemArray{
        let composeItem = LS_ComposeItem(dict: item)
         //添加到数组
            array.append(composeItem)
        }
       return array
    }()

    }
